package com.dc.docs._888_面试.concurrent._9_synchronized;

/**
 * Description: Synchronized 修饰代码块_对象（锁的是操作对象）
 * @author: gdc
 * @date: 2021/6/17
 * @version 1.0
 */
public class SyncCodeBlock_Obj_Demo implements Runnable {

    /**
     * 资源
     */
    private int num = 0;

    /**
     * 增加方法
     */
    public void increase(){
        num++;
    }

    @Override
    public void run() {
        for (int z = 0; z < 10000; z++) {
            // 此处 synchronized 修饰的this, 锁为当前对象
            synchronized (this) {
                increase();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        SyncCodeBlock_Obj_Demo syncObj = new SyncCodeBlock_Obj_Demo();

        // 此处需要确保线程操作的是同一个对象
        Thread thread1 = new Thread(syncObj);
        Thread thread2 = new Thread(syncObj);

        thread1.start();
        thread2.start();

        // join()方法：表示调用线程等待该线程完成后，才能继续向下运行
        // 下面的案例可以理解：main线程需要等待 thread1、thread2线程执行完之后，才能执行
        thread1.join();
        thread2.join();

        System.out.println(syncObj.num);
    }
}
